<!-- test02.vue 修改内容 -->
<template>
  <div class="upload-image-container">
    <!-- 已上传图片展示区域 -->
    <div class="uploaded-images">
      <!-- 原有的图片 -->
      <div
        class="uploaded-image-item"
        v-for="(file, index) in originFiles"
        :key="index">
        <img
          :src="file.url"
          :alt="'上传的图片 ' + (index + 1)"
          class="uploaded-img" />
        <div
          class="delete-btn"
          @click="handleDeleteOriginImage(file.id, index)"
          aria-label="删除图片">
          <i class="fas fa-times"></i>
        </div>
      </div>
      <!-- 上传的图片 -->
      <div
        class="uploaded-image-item"
        v-for="(file, index) in uploadedFiles"
        :key="index">
        <img
          :src="file.previewUrl"
          :alt="'上传的图片 ' + (index + 1)"
          class="uploaded-img" />
        <button
          class="delete-btn"
          @click="handleDelete(index)"
          aria-label="删除图片">
          <i class="fas fa-times"></i>
        </button>
      </div>
      <!-- 上传区域 -->
      <label class="upload-area" @click="handleClickUpload">
        <div class="upload-placeholder">
          <i class="fas fa-cloud-upload-alt upload-icon"></i>
          <p class="upload-tip">点击此处上传</p>
          <p class="format-tip">支持 JPG、PNG 格式，单张不超过 2M</p>
        </div>
        <input
          type="file"
          :accept="acceptTypesString"
          @change="handleFileChange"
          class="upload-input"
          ref="fileInput"
          multiple />
        <!-- 修改：添加multiple支持多文件上传 -->
      </label>
    </div>

    <!-- <button @click="this.handleUploadToServer()">上传图片</button> -->
  </div>
</template>

<script>
import FileUploadUtil from "@/utils/upload.js"; // 修改：引入上传工具类
import axios from "axios";
import { getToken } from "@/utils/auth";
export default {
  name: "UploadImage",
  data() {
    return {
      // 存储已上传的文件信息
      uploadedFiles: [],
      acceptTypes: ["image/jpeg", "image/png"], // 修改：定义接受的文件类型
      uploadUtil: new FileUploadUtil(), // 修改：创建上传工具类实例
    };
  },
  props: {
    originFiles: {
      type: Array,
      default: () => [],
    },
    skuId: {
      type: Number,
      default: () => 90,
    },
  },
  watch: {
    originFiles: {
      immediate: true,
      handler(newVal) {
        console.log("originFiles changed:", newVal);
      },
    },
  },
  computed: {
    // 修改：计算属性生成accept字符串
    acceptTypesString() {
      return this.acceptTypes.join(",");
    },
  },
  methods: {
    // 点击上传区域触发文件选择
    handleClickUpload() {
      // this.$refs.fileInput.click();
    },
    // 处理文件选择变化
    handleFileChange(e) {
      const files = e.target.files;
      if (files && files.length > 0) {
        // 修改：循环处理多个文件
        Array.from(files).forEach((file) => {
          this.handleFile(file);
        });
        // 清空输入框，以便再次选择同一文件能触发change事件
        e.target.value = "";
      }
    },
    // 修改：使用工具类处理文件
    handleFile(file) {
      // 使用工具类验证并处理文件
      this.uploadUtil.handleFileUpload(file, {
        maxSize: 2 * 1024 * 1024, // 2MB
        acceptTypes: this.acceptTypes,
      });

      // 检查是否有错误
      if (this.uploadUtil.error) {
        alert(this.uploadUtil.error);
        return;
      }

      // 监听文件处理完成
      this.uploadUtil.reader.onloadend = () => {
        // 将处理好的文件添加到已上传列表
        this.uploadedFiles.push({
          file: this.uploadUtil.file,
          previewUrl: this.uploadUtil.previewUrl,
        });

        // 调用上传到服务器的方法
      };
    },
    // 修改：使用工具类上传到服务器
    handleUploadToServer() {
      // 示例：上传到服务器，实际项目中替换为真实URL
      console.log("有狗点我阿");
      this.uploadUtil
        .uploadToServer("http://localhost:8092/product/productImage/upload", {
          skuId: this.skuId,
        })
        .then((response) => {
          console.log("上传成功", response);
          return response;
        })
        .catch((error) => {
          console.error("上传失败", error);
          alert(error.message);
        });
    },
    // 删除已上传图片
    handleDelete(index) {
      // 释放预览URL资源
      URL.revokeObjectURL(this.uploadedFiles[index].previewUrl);
      this.uploadedFiles.splice(index, 1);
    },
    handleDeleteOriginImage(imageId, index) {
      axios
        .delete(
          `http://localhost:8092/product/productImage/delete/${imageId}`,
          {
            headers: {
              Authorization: "Bearer " + getToken(),
            },
          }
        )
        .then((response) => {
          console.log("删除成功", response);
          this.originFiles.splice(index, 1);
        })
        .catch((error) => {
          console.error("删除失败", error);
        });
    },
  },
  beforeDestroy() {
    // 修改：组件销毁时清理资源
    this.uploadedFiles.forEach((item) => {
      URL.revokeObjectURL(item.previewUrl);
    });
  },
};
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
.upload-image-container {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  width: 100%;
  padding: 20px;
}

.uploaded-images {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 15px;
}

.uploaded-image-item {
  position: relative;
  width: 150px;
  height: 150px;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;

  &:hover {
    transform: scale(1.03);
  }
}

.uploaded-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.8);
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #ff4d4f;
  transition: all 0.2s ease;

  &:hover {
    background-color: #fff;
    transform: scale(1.1);
  }

  i {
    font-size: 14px;
  }
}

.upload-area {
  display: block;
  width: 150px;
  height: 150px;
  border: 2px dashed #ccc;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  background-color: #fafafa;

  &:hover {
    border-color: #409eff;
    background-color: #f5f7fa;
  }
}

.upload-placeholder {
  text-align: center;
  padding: 0 0;
}

.upload-icon {
  font-size: 40px;
  color: #999;
  margin-bottom: 12px;
  transition: color 0.3s ease;

  .upload-area:hover & {
    color: #409eff;
  }
}

.upload-tip {
  font-size: 16px;
  color: #666;
  margin: 0 0 8px 0;
}

.format-tip {
  font-size: 13px;
  color: #999;
  margin: 0;
}

.upload-input {
  display: none;
}
</style>
